#include <iostream>
#include <memory>
#include <string>
#include "Reactor.hpp"
#include "Listener.hpp"
#include "HandlerConnection.hpp"
#include "PackageParse.hpp"


int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        std::cerr << "Usage: " << argv[0] << " port" << std::endl;
    }
    uint16_t port = std::stoi(argv[1]);
    InetAddr local("0.0.0.0", port);
    PackageParse parse;


    // 负责处理新连接到来的模块
    Listener listener(port); // 连接管理器

    // 负责处理普通连接的模块
    HandlerConnection handler(std::bind(&PackageParse::Excute, &parse, std::placeholders::_1)); // IO处理器

    // 主模块，事件派发
    std::unique_ptr<Reactor> R = std::make_unique<Reactor>(); // 事件派发器
    
    // 添加处理不同连接的接口，使模块之间产生联系
    R->SetOnConnect(std::bind(&Listener::Accepter, &listener, std::placeholders::_1)); // 处理新连接
    R->SetOnNormalHandler(
        std::bind(&HandlerConnection::HandlerReceiver, &handler, std::placeholders::_1), 
        std::bind(&HandlerConnection::HandlerSender, &handler, std::placeholders::_1), 
        std::bind(&HandlerConnection::HandlerExcepter, &handler, std::placeholders::_1)
    );

    // 将listensock连接添加到 reactor
    R->AddConnection(listener.GetSockfd(), EPOLLIN|EPOLLET, local, ListenSock);
    
    // 开始运行
    R->Dispatcher();
}